package com.xiaocz.hblsubstitutedriving;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.Marker;
import com.bumptech.glide.Glide;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;
import com.hedan.textdrawablelibrary.TextViewDrawable;
import com.vise.log.ViseLog;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.utils.SPUtil;
import com.xiaocz.common.utils.SignUtil;
import com.xiaocz.common.utils.TimeUtil;
import com.xiaocz.common.widgets.CircleImageView;
import com.xiaocz.common.widgets.dialog.CustomDialog;
import com.xiaocz.hblsubstitutedriving.activities.activity.AuthenticationActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.CustomerCenterActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.ExpenseStandardActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.LaunchActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.LoginActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.MyAccountActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.OrderCourseActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.OrderGatheringActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.OrderListActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.PersonalDetailsActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.VipActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.WebViewActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.dialog.AdvertisingActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.dialog.DialogBadgeActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.dialog.DialogSweepOrderActivity;
import com.xiaocz.hblsubstitutedriving.activities.fragment.HomeFragment;
import com.xiaocz.hblsubstitutedriving.activities.fragment.MapFragment;
import com.xiaocz.hblsubstitutedriving.activities.fragment.dialog.CreateOrderDialogFragment;
import com.xiaocz.hblsubstitutedriving.activities.navi.NavigationCustomActivity;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.base.Fragment;
import com.xiaocz.hblsubstitutedriving.interfaces.BeRobbedUtils;
import com.xiaocz.hblsubstitutedriving.interfaces.CancelUtils;
import com.xiaocz.hblsubstitutedriving.interfaces.MainUtils;
import com.xiaocz.hblsubstitutedriving.interfaces.RoundRefresh;
import com.xiaocz.hblsubstitutedriving.interfaces.RoundRefreshUtils;
import com.xiaocz.hblsubstitutedriving.location.MyLocation;
import com.xiaocz.hblsubstitutedriving.model.CloudOrder;
import com.xiaocz.hblsubstitutedriving.model.OrderPay;
import com.xiaocz.hblsubstitutedriving.model.SkDriver;
import com.xiaocz.hblsubstitutedriving.model.UndoneOrder;
import com.xiaocz.hblsubstitutedriving.model.UserInfo;
import com.xiaocz.hblsubstitutedriving.socket.TaskCenter;
import com.xiaocz.hblsubstitutedriving.utils.AppUtil;
import com.xiaocz.hblsubstitutedriving.utils.Constants;
import com.xiaocz.hblsubstitutedriving.widget.NoScrollViewPager;
import com.xiaocz.hblsubstitutedriving.wxapi.Wechat;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements View.OnClickListener, RoundRefresh {

    /**
     * UI
     */
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.nav)
    LinearLayout navigationView;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_start_work)
    TextView tvStartWork;
    @BindView(R.id.iv_head_portrait)
    CircleImageView circleImageView;

    @BindView(R.id.tv_recommend)
    TextView tv_recommend;//推荐客户


    @BindView(R.id.tab_layout)
    SlidingTabLayout mTabLayout;
    @BindView(R.id.view_pager)
    NoScrollViewPager mViewPager;

    private long mExitTime;
    private boolean isOne;

    public static void show(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initWidgets() {
        ImmersionBar.setTitleBar(this, findViewById(R.id.top_view));
        mViewPager.setNoScroll(true);
        isUserState(false);
        socketListener();
        MainUtils.setMainfresh(this);
        getUpdateVersion();
    }

    /**
     * 云订单-消息-权限
     */
    private void checkDialogService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(getApplicationContext())) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("提示");
                builder.setCancelable(false);
                builder.setMessage("请打开系统对话框权限，以保证正常接收线上单！");
                builder.setNegativeButton("去开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivityForResult(
                                new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                        Uri.parse("package:" + getPackageName())), 100);
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            } else {
                dialogReceive();
            }
        } else {
            dialogReceive();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                    && !Settings.canDrawOverlays(mContext)) {//失败
                App.getInstance().showMessage("打开系统对话框权限失败！");
            } else {//成功
                dialogReceive();
            }
        }
    }

    @OnClick({R.id.left_btn, R.id.right_btn, R.id.btn_badge, R.id.tv_start_work, R.id.tv_account, R.id.tv_personal_details,
            R.id.tv_expense, R.id.btn_create_order, R.id.tv_order, R.id.tv_jjbz, R.id.tv_share, R.id.tv_jc, R.id.btn_exit,
            R.id.tv_contact_number, R.id.btn_smxd, R.id.btn_1, R.id.btn_2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_btn://更多
                drawerLayout.openDrawer(navigationView);
                break;
            case R.id.right_btn:
//                App.getInstance().showMessage("暂无消息");
                Intent intent = new Intent();
                intent.setClass(mContext, NavigationCustomActivity.class);
//                startActivity(intent);
                AdvertisingActivity.show(mContext);
                break;
            case R.id.tv_start_work://开始听单
                checkDialogService();
                break;
            case R.id.btn_create_order://创建订单
                showCreateOrderDialogFragment();
                break;
            /*-------------抽屉部分START-----------------*/
            case R.id.tv_personal_details://我的资料
                PersonalDetailsActivity.show(mContext);
                break;
            case R.id.tv_account://账户
                MyAccountActivity.show(mContext);
                break;
            case R.id.tv_expense://司机月费
                VipActivity.show(mContext);
                break;
            case R.id.tv_order://订单
                OrderListActivity.show(mContext);
                break;
            case R.id.tv_contact_number://客服热线
                CustomerCenterActivity.show(mContext);
                break;
            case R.id.tv_jjbz://计价标准
                ExpenseStandardActivity.show(mContext);
                break;
            case R.id.tv_share://分享
                onDialogShareContentType();
                break;
            case R.id.tv_jc://使用教程
                WebViewActivity.show(mContext, Common.Constant.API_H5 + "apph5/help");
                break;
            case R.id.btn_exit://退出
                if (tvStartWork.getText().toString().contains("听单中")) {
                    dialogExit();
                } else {
                    dialogExits();
                }
                break;/*-------------抽屉部分END-----------------*/
            case R.id.btn_badge://电子工牌
                DialogBadgeActivity.show(mContext);
                break;
            case R.id.btn_smxd://扫描下单
                DialogSweepOrderActivity.show(mContext);
                break;
            case R.id.btn_1://发布补位
                App.getInstance().showMessage("正在开发中");
                break;
            case R.id.btn_2://联系司管
                callPhone(null);
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        List<String> mTabTitleTexts = new ArrayList<>();
        mTabTitleTexts.add("工作台");
        mTabTitleTexts.add("地图");
        List<Fragment> mTabFragments = new ArrayList<>();
        UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
        StringBuilder stringUrl = new StringBuilder();
        Map<String, Object> formDataMap = new HashMap<>();
        if (info != null) {
            formDataMap.put("ranstr", "android");
            formDataMap.put("timestamp", TimeUtil.getStringStamp());
            stringUrl.append(Common.Constant.API_H5 + "apph5/Index?driver_id=");
            stringUrl.append(info.getId());
            stringUrl.append("&ranstr=");
            stringUrl.append(formDataMap.get("ranstr"));
            stringUrl.append("&timestamp=");
            stringUrl.append(formDataMap.get("timestamp"));
            stringUrl.append("&sign=");
            stringUrl.append(SignUtil.createSign(formDataMap));
        }
        mTabFragments.add(HomeFragment.newInstance(stringUrl.toString()));
        mTabFragments.add(MapFragment.newInstance());
        mViewPager.setOffscreenPageLimit(mTabFragments.size());
        mViewPager.setAdapter(new MyViewPagerAdapter(
                getSupportFragmentManager(),
                mTabFragments,
                mTabTitleTexts));
        mTabLayout.setViewPager(mViewPager);//绑定
//        Intent intent = new Intent(getApplicationContext(), BackstageService.class);
//        startService(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        undoneOrder();
    }

    @Override
    protected void initData() {
        super.initData();
        TaskCenter.sharedCenter().setDisconnectedCallback(new TaskCenter.OnServerDisconnectedCallbackBlock() {
            @Override
            public void callback(Exception e) {
                if (Constants.isRelink) {
                    Constants.isWork = false;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isEmpty(tvStartWork)) {
                            if (!tvStartWork.getText().toString().contains("开启听单")) {
                                if (Constants.isRelink) {
                                    App.getInstance().showMessage("系统检测到你的网络有波动，" +
                                            "或流量信号太差，你可以检查网络或重新登录上线", Toast.LENGTH_LONG);
                                } else {
                                    App.getInstance().audioFocus(R.raw.tztd, true);
                                    tvStartWork.setText("开启听单");
                                    tvStartWork.setBackgroundColor(ContextCompat.getColor(mContext, R.color.textColorThird));
                                    onDismiss();
                                }
                            } else {
                                if (!Constants.isRelink) {
                                    tvStartWork.setText("开启听单");
                                    tvStartWork.setBackgroundColor(ContextCompat.getColor(mContext, R.color.textColorThird));
                                }
                            }
                        }
                    }
                });
            }
        });
        TaskCenter.sharedCenter().setConnectedCallback(new TaskCenter.OnServerConnectedCallbackBlock() {
            @Override
            public void callback() {
                SkDriver skDriver = new SkDriver();
                UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
                if (info != null) {
                    if (Constants.location != null && Constants.location.getProvince() != null) {
                        skDriver.setDriver_id(info.getId());
                        skDriver.setDriver_name(info.getTruename());
                        skDriver.setPhone(info.getPhone());
                        skDriver.setProvincecity(Constants.location.getProvince());
                        skDriver.setLongitude(Constants.location.getLongitude());
                        skDriver.setLatitude(Constants.location.getLatitude());
                        skDriver.setWorkstatus(Constants.driverWorkState);
                        TaskCenter.sharedCenter().sendMessage("DriverUpdateLocation", new Gson().toJson(skDriver));
                    }
                }
            }
        });
        if (Constants.location != null && Constants.location.getProvince() != null && Constants.location.getCity() != null) {
            getSocket(Constants.location.getProvince(), Constants.location.getCity());
        }
    }

    private boolean isEmpty(View view) {
        if (view != null) {
            return true;
        } else {
            App.getInstance().showMessage("请重新登录！");
            AccountManagers.logOut();
            AppUtil.finishAll();
            LaunchActivity.show(mContext);
            return false;
        }
    }


    @Override
    public void onRoundRefresh(int type, String message) {
        if (type == 1) {
            if (Constants.isRelink) {
                Constants.isWork = true;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!tvStartWork.getText().toString().contains("听单中")) {
                        if (isOne) {
                            isOne = false;
                            App.getInstance().audioFocus(R.raw.kstd, true);
                            onDismiss();
                        }
                    }
                    tvStartWork.setText("听单中，点击下线");
                    tvStartWork.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
                }
            });
        } else {
            if (Constants.isRelink) {
                Constants.isWork = false;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (tvStartWork != null) {
                        tvStartWork.setText("开启听单");
                        tvStartWork.setBackgroundColor(ContextCompat.getColor(mContext, R.color.textColorThird));
                    }
                }
            });
        }
    }

    /**
     * 司机状态
     */
    private void dialogVip(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("参加会员", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                VipActivity.show(mContext);
                dialog.dismiss();
            }
        });
//        builder.setNeutralButton("不再提醒", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                SPUtil.put("BZTX",true);
//                dialog.dismiss();
//            }
//        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        if (!Boolean.parseBoolean(SPUtil.get("BZTX", false).toString())) {
            builder.create().show();
        }
    }

    /**
     * 司机权限
     */
    private void onDialog(String address) {
        final AlertDialog dialog = new AlertDialog.Builder(mContext).create();
        dialog.show();
        dialog.setCancelable(false);
        Window window = dialog.getWindow();
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (inflater != null && window != null) {
            View view = inflater.inflate(R.layout.activity_authentication_on, null);
            view.findViewById(R.id.layout_update_info).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AuthenticationActivity.show(mContext);
                }
            });
            view.findViewById(R.id.layout_tel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callPhone(null);
                }
            });
            view.findViewById(R.id.tv_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    AppUtil.finishAll();
                    LoginActivity.show(mContext);
                }
            });
            TextViewDrawable tVAddress = view.findViewById(R.id.tv_address);
            if (address == null || "".equals(address)) {
                tVAddress.setVisibility(View.GONE);
            } else {
                tVAddress.setText(String.valueOf("司管公司地址：" + address));
            }
            WindowManager.LayoutParams attributes = window.getAttributes();
            window.setAttributes(attributes);
            window.setContentView(view);
        }
    }

    /**
     * 听单
     */
    private void dialogReceive() {
        UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
        try {
            if(info.getOrderPattern()==2 && dateFormat.parse(info.getExpiretime()).getTime() / 1000L < TimeUtil.getLongStamp()){
                dialogVip("您的司机会员资格尚未开通，请开通后再听单！");
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        if (Constants.isWork) {
            builder.setMessage("确认停止工作？");
        } else {
            builder.setMessage("确认开始工作？");
        }
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Constants.isWork) {
                    isOne = false;
                    removeMarker();
                    if (Constants.getLocation() != null) {
                        SkDriver skDriver = new SkDriver();
                        skDriver.setDriver_id(AccountManagers.getUserId());
                        skDriver.setProvincecity(Constants.getLocation().getProvince());
                        TaskCenter.sharedCenter().sendMessage("DriverOut", new Gson().toJson(skDriver));
                    } else {
                        App.getInstance().showMessage(getResources().getString(R.string.none_location));
                    }
                } else {
                    isUserState(true);
                }
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public static ArrayList<Marker> markerList = null;

    /**
     * 移除司机头像
     */
    public static void removeMarker() {
        if (markerList != null) {
            for (int j = 0; j < markerList.size(); j++) {
                markerList.get(j).remove();
            }
        }
    }

    /**
     * 获取未完成订单
     */
    private void undoneOrder() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/queryDriverOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<UndoneOrder>>() {
                }.getType();
                RspModel<UndoneOrder> rspModel = getAnalysis(response, type, "获取未完成订单");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !rspModel.isStatus()) {
                            UndoneOrder undoneOrder = rspModel.getData();
                            if (undoneOrder.getOrderstatus() == 3) {//已完成 未付款
                                getNoPay(undoneOrder.getOrderNo());
                            } else {//未完成（进入订单流程）
                                getUndoneOrder(undoneOrder.getOrderNo());
                            }
                            Constants.driverWorkState = "2";//修改司机状态为忙碌状态
                        } else {
                            Constants.driverWorkState = "1";//修改司机状态为空闲状态
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TaskCenter.sharedCenter().stopSocket();
        Constants.isRelink = false;
        Constants.isWork = false;
        MyLocation myLocation = MyLocation.getInstance();
        myLocation.destroyLocation();
    }

    private AlertDialog alertDialog, alertDialogUndoneOrder;

    /**
     * 提示去完成-未完成订单
     */
    private void getUndoneOrder(final String undoneOrder) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提醒");
        builder.setCancelable(false);
        builder.setMessage("您有未完成订单");
        builder.setNegativeButton("去完成", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                OrderCourseActivity.show(mContext, undoneOrder);
                alertDialog.dismiss();
            }
        });
        alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 未付款（1-强制付款，2-提示付款）
     */
    private void getNoPay(final String undoneOrder) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提醒");
        builder.setCancelable(false);
        builder.setMessage("您有订单未收款！");
        builder.setNegativeButton("去收款", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                OrderGatheringActivity.show(mContext, undoneOrder);
                alertDialogUndoneOrder.dismiss();
            }
        });
        alertDialogUndoneOrder = builder.create();
        alertDialogUndoneOrder.show();
    }

    /**
     * 定义内部的适配器类
     */
    private static class MyViewPagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> mTabFragments;
        private List<String> mTabTitleTexts;

        private MyViewPagerAdapter(FragmentManager fm, List<Fragment> tabFragments, List<String> tabTitleTexts) {
            super(fm);
            mTabFragments = tabFragments;
            mTabTitleTexts = tabTitleTexts;
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return mTabFragments.get(position);
        }


        @Override
        public int getCount() {
            return mTabFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTabTitleTexts.get(position);
        }

    }

    /**
     * 退出
     */
    private void dialogExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage("您正在听单状态，请先停止听单，再退出！");
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 退出
     */
    private void dialogExits() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage("即将退出软件！");
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //mContext.stopService(new Intent(mContext, BackstageService.class));// 关闭服务
                AccountManagers.logOut();
                AppUtil.finishAll();
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }


    /**
     * 分享类型
     */
    private void onDialogShareContentType() {
        final CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_share_content_type, null);
        builder.setContentView(layout);
        builder.setGravity(Gravity.BOTTOM);
        builder.setDialogWidthAndPX(WindowManager.LayoutParams.MATCH_PARENT);
        builder.setDialogHeightAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        final CustomDialog dialog = builder.create();
        dialog.show();
        layout.findViewById(R.id.wx_hy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onDialogShare(Common.Constant.API_H5 + "apph5/customershare");
                dialog.dismiss();
            }
        });
        layout.findViewById(R.id.wx_pyq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onDialogShare(Common.Constant.API_H5 + "apph5/drivershare");
                dialog.dismiss();
            }
        });
        layout.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 分享
     */
    private void onDialogShare(final String content) {
        final CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_share, null);
        builder.setContentView(layout);
        builder.setGravity(Gravity.BOTTOM);
        builder.setDialogWidthAndPX(WindowManager.LayoutParams.MATCH_PARENT);
        builder.setDialogHeightAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        final CustomDialog dialog = builder.create();
        dialog.show();
        layout.findViewById(R.id.wx_hy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
                Wechat.share(mContext, "自己人代驾", "新代驾、更便宜、更安全", content, bitmap, 0);
                dialog.dismiss();
            }
        });
        layout.findViewById(R.id.wx_pyq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
                Wechat.share(mContext, "自己人代驾", "新代驾、更便宜、更安全", content, bitmap, 1);
                dialog.dismiss();
            }
        });
        layout.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 司机状态
     */
    private void dialogWork(String message, final boolean isXz) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请联系您的司管");
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("联系司管", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                callPhone(null);
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isXz) {
                    dialog.dismiss();
                } else {
                    AppUtil.finishAll();// 否则退出程序
                }
            }
        });
        builder.create().show();
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat(Common.DateType.dateIF, Locale.CHINA);
    /**
     * 用户-权限判断-并听单
     */
    private void isUserState(boolean isTd) {
        UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
        if (info != null) {
            Glide.with(mContext)
                    .load(info.getHeadPictureUrl()).apply(Constants.getOptions())
                    .into(circleImageView);
            switch (info.getAuthentication()) {
                case 0://是否已认证 0-未认证 1-已认证 2-待认证 3-待总部认证
                    AuthenticationActivity.show(mContext);
                    finish();
                    break;
                case 2:
                case 3:
                    onDialog(info.getAddress());
                    break;
                case 1:
                    if (info.getStatus() == 1) {
                        dialogWork("账号已被冻结", false);
                    } else {
                        if (info.getLimitWork() == 1) {
                            dialogWork("账号已被限制" + info.getLimitTime_start() + "至" + info.getLimitTime_end(), true);
                        } else {
                            if (isTd) {
                                TaskCenter.sharedCenter().startSocket("开始听单");
                                Constants.isRelink = true;//开启断开重连
                                loadingDialogShow(true);
                                isOne = true;
                            }
                            if (!isTd) {
                                switch (info.getOrderPattern()) {
                                    case 1://按单提成
                                        break;
                                    case 2://包月模式
                                        try {
                                            if (info.getExpiretime() == null || info.getOrderPattern()==1) {
                                                return;
                                            }
                                            if (dateFormat.parse(info.getExpiretime()).getTime() / 1000L < TimeUtil.getLongStamp()) {
                                                if (TimeUtil.getLongStamp() - dateFormat.parse(info.getExpiretime()).getTime() / 1000L <= 259200) {
                                                    dialogVip("您的会员资格即将到期，到期后将无法接单做单！");
                                                }
                                            } else {
                                                if (dateFormat.parse(info.getExpiretime()).getTime() / 1000L < TimeUtil.getLongStamp() + 259200) {
                                                    long time = dateFormat.parse(info.getExpiretime()).getTime() / 1000L - TimeUtil.getLongStamp();
                                                    long hour = time / (60 * 60);
                                                    long day = hour / 24;
                                                    if (day > 0) {
                                                        dialogVip("会员资格" + day + "天" + hour % 24 + "小时后到期，到期后将无法接单做单！");
                                                    } else {
                                                        if (day == 0) {
                                                            dialogVip("您的会员资格已到期，到期后将无法接单做单！");
                                                        } else {
                                                            dialogVip("会员资格" + hour + "小时后到期，到期后将无法接单做单！");
                                                        }
                                                    }
                                                }
                                            }
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                        break;
                                    case 3://混合模式
                                        try {
                                            if (info.getExpiretime() == null || info.getOrderPattern()==1) {
                                                return;
                                            }
                                            if (dateFormat.parse(info.getExpiretime()).getTime() / 1000L < TimeUtil.getLongStamp()) {
                                                if (TimeUtil.getLongStamp() - dateFormat.parse(info.getExpiretime()).getTime() / 1000L <= 259200) {
                                                    dialogVip("您的会员资格即将到期，到期后将默认按单扣费，若需继续使用会员模式，请重新参加会员！");
                                                }
                                            } else {
                                                if (dateFormat.parse(info.getExpiretime()).getTime() / 1000L < TimeUtil.getLongStamp() + 259200) {
                                                    long time = dateFormat.parse(info.getExpiretime()).getTime() / 1000L - TimeUtil.getLongStamp();
                                                    long hour = time / (60 * 60);
                                                    long day = hour / 24;
                                                    if (day > 0) {
                                                        dialogVip("会员资格" + day + "天" + hour % 24 + "小时后到期，到期后将按单扣费，若需继续使用会员模式，请重新参加会员！");
                                                    } else {
                                                        if (day == 0) {
                                                            dialogVip("您的会员资格已到期，到期后将默认按单扣费，若需继续使用会员模式，请重新参加会员！");
                                                        } else {
                                                            dialogVip("会员资格" + hour + "小时后到期，到期后将按单扣费，若需继续使用会员模式，请重新参加会员！");
                                                        }
                                                    }
                                                }
                                            }
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                        break;
                                }
                            }
                        }
                    }
                    break;
            }
            if(info.getRecommend()==0){
                tv_recommend.setVisibility(View.GONE);
            }else {
                tv_recommend.setVisibility(View.VISIBLE);
                tv_recommend.setText(String.format("推荐新客户扫您码下单,该客户前%s单每单分成%s元",info.getRecommendNumber(),info.getRecommendMoney()));
            }
            tvName.setText(info.getPhone());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 用户按下返回按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mExitTime > 2000L) {
                mExitTime = System.currentTimeMillis();
                App.getInstance().showMessage("再按一下将退出");
            } else {
                //mContext.stopService(new Intent(mContext, BackstageService.class));// 关闭服务
                // 否则退出程序
                AppUtil.finishAll();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 创建订单
     */
    private void showCreateOrderDialogFragment() {
        CreateOrderDialogFragment fragment = CreateOrderDialogFragment.newInstance();
        if (!fragment.isAdded()) {
            fragment.show(getSupportFragmentManager(), fragment.getClass().getName());
        }
    }

    /**
     * socket监听
     */
    private void socketListener() {
        TaskCenter.sharedCenter().setReceivedCallback(new TaskCenter.OnReceiveCallbackBlock() {
            @Override
            public void callback(String receicedMessage) {
                receicedMessage = receicedMessage.replace("&", "").trim();
                if ("心跳".equals(receicedMessage)) {//心跳
                } else if (receicedMessage.contains("DriverUpdateLocation")) {//当前位置上传成功
                    if (receicedMessage.contains("DriverUpdateLocationok")) {
                        MainUtils.onMainRefresh(1, receicedMessage);
                    } else {
                        MainUtils.onMainRefresh(2, receicedMessage);
                    }
                } else if (receicedMessage.contains("QueryNearDrivers")) {//附近司机
                    ViseLog.i("-----xx附近司机：" + receicedMessage);
                    RoundRefreshUtils.onPushRefresh(1, receicedMessage.replace("QueryNearDrivers", ""));
                } else if (receicedMessage.contains("QRCodeOrder")) {//扫码单
                    powerManager();
                    ViseLog.i("-----xx扫码单：" + (new Gson().fromJson(receicedMessage.replace("QRCodeOrder", ""), CloudOrder.class)));
                    Intent mIntent = new Intent(mContext, FTService.class);
                    mIntent.putExtra("cloudOrder", new Gson().fromJson(receicedMessage.replace("QRCodeOrder", ""), CloudOrder.class));
                    stopService(mIntent);
                    startService(mIntent);
                    App.getInstance().showMessage("有新的扫码单");
                    App.getInstance().audioFocus(R.raw.ldtx, true);
                } else if (receicedMessage.contains("YunOrder")) {//云订单
                    powerManager();
                    ViseLog.i("-----xx新订单：" + (new Gson().fromJson(receicedMessage.replace("YunOrder", ""), CloudOrder.class)));
                    Intent mIntent = new Intent(mContext, FTService.class);
                    mIntent.putExtra("cloudOrder", new Gson().fromJson(receicedMessage.replace("YunOrder", ""), CloudOrder.class));
                    stopService(mIntent);
                    startService(mIntent);
                    App.getInstance().showMessage("有新的订单");
                    App.getInstance().audioFocus(R.raw.ldtx, true);
                } else if (receicedMessage.contains("OrderCancel")) {//客户取消订单
                    powerManager();
                    ViseLog.i("----------xx取消订单" + receicedMessage.replace("OrderCancel", ""));
                    App.getInstance().audioFocus(R.raw.kh_qxdd, true);
                    Constants.driverWorkState = "1";//修改司机状态为空闲状态
                    CancelUtils.onCancelRefresh(30, receicedMessage.replace("OrderCancel", ""));
                    if (alertDialog != null) {
                        alertDialog.dismiss();
                    }
                } else if (receicedMessage.contains("WeChatPaySuccess")) {//支付提醒
                    powerManager();
                    ViseLog.i("-----------xx收到微信付款：" + receicedMessage);
                    App.getInstance().audioFocus(R.raw.khwxzf, true);
                    OrderPay orderPay = new Gson().fromJson(receicedMessage.replace("WeChatPaySuccess", ""), OrderPay.class);
                    if (CancelUtils.onPayRefresh(40, orderPay.getMoney()) == null) {
                        App.getInstance().showMessage("收到付款" + orderPay.getMoney() + "元");
                    }
                    if (alertDialogUndoneOrder != null) {
                        alertDialogUndoneOrder.dismiss();
                    }
                } else if (receicedMessage.contains("DriverOutok")) {//断开连接
                    ViseLog.i("-----------xx关闭接单：" + receicedMessage);
                    TaskCenter.sharedCenter().releaseSocket();
                    Constants.isRelink = false;//关闭断开重连
                } else if (receicedMessage.contains("OrderRobbed")) {//订单被已抢
                    ViseLog.i("-----------xx已被抢：" + receicedMessage);
                    BeRobbedUtils.onCancelRefresh(99, receicedMessage);
                } else {
                    ViseLog.i("---------xx收到其他內容：" + receicedMessage);
                }
            }
        });
    }

    /**
     * 点亮屏幕
     */
    private void powerManager() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (pm == null){
            return;
        }
        PowerManager.WakeLock
                wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "messagelisenter:bright");
        wl.acquire(1000);
        wl.release();
    }
}